package com.ruoyi.stock.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.WxV3PayConfig;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.IsOrNo;
import com.ruoyi.common.enums.memberTypeEnums;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.wx.WXPayUtil;
import com.ruoyi.common.utils.wx.WxMiniPayUtils;
import com.ruoyi.stock.domain.StockMemberOrder;
import com.ruoyi.stock.domain.StockMemberRule;
import com.ruoyi.stock.domain.StockUser;
import com.ruoyi.stock.mapper.StockMemberOrderMapper;
import com.ruoyi.stock.service.IStockMemberOrderService;
import com.ruoyi.stock.service.IStockMemberRuleService;
import com.ruoyi.stock.service.IStockUserService;
import com.ruoyi.system.service.ISysUserService;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 订单Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-12-30
 */
@Service
public class StockMemberOrderServiceImpl implements IStockMemberOrderService 
{
    @Autowired
    private StockMemberOrderMapper stockMemberOrderMapper;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IStockMemberRuleService stockMemberRuleService;



    @Autowired
    private IStockUserService stockUserService;

    /**
     * 查询订单
     * 
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public StockMemberOrder selectStockMemberOrderById(Long id)
    {

        return stockMemberOrderMapper.selectStockMemberOrderById(id);
    }

    /**
     * 查询订单列表
     * 
     * @param stockMemberOrder 订单
     * @return 订单
     */
    @Override
    public List<StockMemberOrder> selectStockMemberOrderList(StockMemberOrder stockMemberOrder)
    {
        return stockMemberOrderMapper.selectStockMemberOrderList(stockMemberOrder);
    }


    @Override
    public StockUser buyOrderUserHandel(StockMemberOrder stockMemberOrder){
        StockMemberRule stockMemberRule= stockMemberRuleService.selectStockMemberRuleById(stockMemberOrder.getMemberCardId());
        StockUser stockUser=new StockUser();
        stockUser.setSysUserid(stockMemberOrder.getUserId());
        stockUser= stockUserService.selectStockUserList(stockUser).get(0);
        stockUser.setIsMember(1);
        stockUser.setInqueryCount(stockMemberRule.getInqueryCount());
        stockUser.setMemberType(memberTypeEnums.正式会员.getCode()+"");
        if(stockMemberOrder.getMemberCardId()==1l){
            stockUser.setIsFreemember(IsOrNo.是.getCode());
            // 免费会员
            stockUser.setMemberType(memberTypeEnums.免费会员.getCode()+"");
        }
        //会员天数叠加
        if(StringUtils.isEmpty(stockUser.getMemberDays())){
            stockUser.setMemberDays("0");
        }
        stockUser.setMemberDays(stockMemberRule.getValidDays()+Integer.parseInt(stockUser.getMemberDays())+"");
        stockUser.setMemberName(stockMemberRule.getName());
        stockUser.setMemberMaturityTime(DateUtils.addDays(new Date(),Integer.parseInt(stockUser.getMemberDays())));
        stockUserService.updateStockUser(stockUser);
        return stockUser;
    }


    //微信支付
    @Override
    public Map<String, Object>   wxStockOrderPay(StockMemberOrder stockMemberOrder) {

        stockMemberOrderMapper.insertStockMemberOrder(stockMemberOrder);

        Map<String, Object> map = new HashMap<>();
        //微信支付
        //支付总金额
        // BigDecimal totalPrice = BigDecimal.ZERO;
        //设置支付金额
        //转换金额保留两位小数点
        //    Double moneyDouble =baOrder.getTotalFee().doubleValue() * 100 ;
        Double moneyDouble=Double.valueOf(stockMemberOrder.getPayMonery())*100;
        int money = (int) Math.floor(moneyDouble);

        try {
            String body = "期权大赢家";
            //完成签名并执行请求
            // SysUser sysUser= SecurityUtils.getLoginUser().getUser();
            SysUser sysUser=userService.selectUserById(SecurityUtils.getUserId());
            // BaUser bauser=new BaUser();
           //   bauser.setSysUserid(SecurityUtils.getUserId());
           //   bauser.setSysUserid(SecurityUtils.getUserId());
            //生成 vx订单id
           // String vxpayOrdernumber = IdUtil.simpleUUID();
           // String openid = sysUser.getOpenId();
            String openid =sysUser.getOpenId();
            JSONObject response = WxMiniPayUtils.creatOrderJSAPI(openid, stockMemberOrder.getOrderNum(), money, body);
            //int statusCode = response.getStatusLine().getStatusCode();
            //log.info("+++++++wx支付response++++++++++++"+ response);
            String bodyResult =response.getString("body");
             System.out.println("+++++++调通支付00000++++++++++++"+ bodyResult);
            JSONObject object = JSONObject.parseObject(bodyResult);
            String  prepayId=object.getString("prepay_id");
            if (StringUtils.isNotEmpty(prepayId)) { //处理成功
                //  String result = EntityUtils.toString(response.getEntity(), "UTF-8");
                //   JSONObject object = JSONObject.parseObject(result);
                //获取预付单
//                 prepayId = object.getString("prepay_id");
//                System.out.println("+++++++调通支付00000prepay_id++++++++++++"+ prepayId);
                //生成签名
                Long timestamp = System.currentTimeMillis() / 1000;
                //随机字符串 这个是微信支付maven自带的 也可以用其它的
                String nonceStr = WXPayUtil.generateNonceStr();
                //生成带签名支付信息
                Map<String, String> param = new HashMap<>();
                param.put("appid", WxV3PayConfig.APP_ID);
                param.put("partnerid", WxV3PayConfig.Mch_ID);
                param.put("packageValue", prepayId);
//                param.put("package", "Sign=WXPay");
                param.put("package", "prepay_id=" + prepayId);
                param.put("nonceStr", nonceStr);
                param.put("timestamp", String.valueOf(timestamp));
                param.put("signType", "MD5");
                // 加密串中包括 appId timeStamp nonceStr package signType 5个参数, 通过sdk WXPayUtil类加密, 注意, 此处使用  MD5加密  方式
                String signatureStr = Stream.of(WxV3PayConfig.APP_ID, String.valueOf(timestamp), nonceStr, "prepay_id=" + prepayId)
                        .collect(Collectors.joining("\n", "", "\n"));
                String sign = WXPayUtil.getSign(signatureStr, WxV3PayConfig.privateKey_Path);
                //String sign = WXPayUtil.getSign(signatureStr, "/www/wwwroot/zhongyi/java/wxPay/apiclient_key.pem");
                //  String sign = WXPayUtil.getSign(signatureStr, "/www/wwwroot/boaomeidi/java/apiclient_key.pem");
                param.put("orderNum", stockMemberOrder.getOrderNum()+"");
                param.put("paySign", sign);
                map.put("code", 200);
                map.put("message", "下单成功");
                map.put("data", param);
                return map;
            }
            map.put("code", 200);
            map.put("message", "下单失败");
            map.put("data", response);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code", 200);
            map.put("message", "下单失败:"+e.getMessage());
            return map;
        }

    }

    @Override
    public Map<String, Object> payNotify(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("+++++++支付回调开始++++++++++++3333"+ response);
        Map<String, Object> map = new HashMap<>();
        try {
            BufferedReader br = request.getReader();
            String str = null;
            StringBuilder sb = new StringBuilder();
            while ((str = br.readLine()) != null) {
                sb.append(str);
            }
            // 构建request，传入必要参数
//            NotificationRequest requests = new NotificationRequest.Builder()
//                    .withSerialNumber(request.getHeader("Wechatpay-Serial"))
//                    .withNonce(request.getHeader("Wechatpay-Nonce"))
//                    .withTimestamp(request.getHeader("Wechatpay-Timestamp"))
//                    .withSignature(request.getHeader("Wechatpay-Signature"))
//                    .withBody(String.valueOf(sb))
//                    .build();
//            //验签
//            NotificationHandler handler = new NotificationHandler(WXPaySignatureCertificateUtil.getVerifier(WxV3PayConfig.mchSerialNo), WxV3PayConfig.apiV3Key.getBytes(StandardCharsets.UTF_8));
//            //解析请求体
//            Notification notification = handler.parse(requests);
//            String decryptData = notification.getDecryptData();



            RequestParam requestParam = new RequestParam.Builder()
                    .serialNumber(request.getHeader("Wechatpay-Serial"))
                    .nonce(request.getHeader("Wechatpay-Nonce"))
                    .signature(request.getHeader("Wechatpay-Signature"))
                    .timestamp(request.getHeader("Wechatpay-Timestamp"))
                    .body(sb.toString())
                    .build();

// 如果已经初始化了 RSAAutoCertificateConfig，可直接使用
// 没有的话，则构造一个
//            NotificationConfig config = new RSAAutoCertificateConfig.Builder()
//                    .merchantId(WxV3PayConfig.Mch_ID)
//                    .privateKeyFromPath(WxV3PayConfig.privateKey_Path)
//                    .merchantSerialNumber(WxV3PayConfig.mchSerialNo)
//                    .apiV3Key(WxV3PayConfig.apiV3Key)
//                    .build();
            NotificationConfig config =
                    new RSAAutoCertificateConfig.Builder()
                            .merchantId(WxV3PayConfig.Mch_ID)
                            // 使用 com.wechat.pay.java.core.util 中的函数从本地文件中加载商户私钥，商户私钥会用来生成请求的签名
                            .privateKeyFromPath(WxV3PayConfig.privateKey_Path)
                            .merchantSerialNumber(WxV3PayConfig.mchSerialNo)
                            .apiV3Key(WxV3PayConfig.apiV3Key)
                            .build();
// 初始化 NotificationParser
            NotificationParser parser = new NotificationParser(config);
             System.out.println("+++++++支付回调开始++++++++++++111111111111111"+ parser);
            Object parseResult= parser.parse(requestParam, Object.class);
            System.out.println("+++++++支付回调开始++++++++++++2222222222222222"+ parseResult);
            Map parseResult1= parser.parse(requestParam, Map.class);
            System.out.println("+++++++支付回调开始++++++++++++3333333333333333"+ parseResult1);
            System.out.println("---------44444444444"+  parseResult1.get("out_trade_no"));
            System.out.println("---------5555555"+  parseResult1.get("transaction_id"));
            //解析
          //  JSONObject jsonObject = JSONObject.parseObject(parseResult.toString());
            //支付状态交易状态，枚举值： SUCCESS：支付成功 REFUND：转入退款 NOTPAY：未支付 CLOSED：已关闭 REVOKED：已撤销（付款码支付）
            // USERPAYING：用户支付中（付款码支付） PAYERROR：支付失败(其他原因，如银行返回失败)trade_state
            String trade_state =  parseResult1.get("trade_state").toString();
            System.out.println("+++++++支付回调成功++++++++++++666666"+ trade_state);//订单号
            if (trade_state.equals("SUCCESS")) {
                System.out.println("+++++++支付回调开始++++++++++++7777777777");//订单号
                String orderNumber = parseResult1.get("out_trade_no").toString();
                StockMemberOrder stockMemberOrder=new StockMemberOrder();
                stockMemberOrder.setOrderNum(orderNumber);
                List<StockMemberOrder> list= stockMemberOrderMapper.selectStockMemberOrderList(stockMemberOrder);
                if(list.size()>0){
                    stockMemberOrder=list.get(0);
                    //处理用户信息
                    buyOrderUserHandel(stockMemberOrder);
                    //改为已支付
                    stockMemberOrder.setOrderState(2l);
                    stockMemberOrder.setPayDate(new Date());
                    stockMemberOrderMapper.updateStockMemberOrder(stockMemberOrder);
                }
                //微信支付微信生成的订单号
                map.put("code", "SUCCESS");
                map.put("message", "成功");
                //消息推送成功
                return map;
            }
            map.put("code", "RESOURCE_NOT_EXISTS");
            map.put("message", "订单不存在");
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("code", "FAIL");
        map.put("message", "失败");
        return map;
    }


    /**
     * 新增订单
     * 
     * @param stockMemberOrder 订单
     * @return 结果
     */
    @Override
    public int insertStockMemberOrder(StockMemberOrder stockMemberOrder)
    {
        stockMemberOrder.setCreateTime(DateUtils.getNowDate());
        return stockMemberOrderMapper.insertStockMemberOrder(stockMemberOrder);
    }

    /**
     * 修改订单
     * 
     * @param stockMemberOrder 订单
     * @return 结果
     */
    @Override
    public int updateStockMemberOrder(StockMemberOrder stockMemberOrder)
    {
        stockMemberOrder.setUpdateTime(DateUtils.getNowDate());
        return stockMemberOrderMapper.updateStockMemberOrder(stockMemberOrder);
    }

    /**
     * 批量删除订单
     * 
     * @param ids 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteStockMemberOrderByIds(Long[] ids)
    {
        return stockMemberOrderMapper.deleteStockMemberOrderByIds(ids);
    }

    /**
     * 删除订单信息
     * 
     * @param id 订单主键
     * @return 结果
     */
    @Override
    public int deleteStockMemberOrderById(Long id)
    {
        return stockMemberOrderMapper.deleteStockMemberOrderById(id);
    }
}
